package com.example.itshome.network;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import com.example.itshome.entity.CommodityEntity;
import com.example.itshome.entity.UserEntity;
import com.example.itshome.manager.UserInfoManager;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;

public class CollectCommodityRequest extends AbstractNetworkRequest{
    //true是收藏 false是取消
    private CommodityEntity isCollect;
    private Button collectButton;
    private int commodityId;
    private Runnable successRunnable;

    public CollectCommodityRequest setSuccessRunnable(Runnable successRunnable) {
        this.successRunnable = successRunnable;
        return this;
    }

    public CollectCommodityRequest setCommodityId(int commodityId) {
        this.commodityId = commodityId;
        return this;
    }

    public CollectCommodityRequest setIsCollect(CommodityEntity isCollect) {
        this.isCollect = isCollect;
        return this;
    }


    public CollectCommodityRequest setCollectButton(Button collectTextView) {
        this.collectButton = collectTextView;
        return this;
    }

    public CollectCommodityRequest(Activity activity) {
        super(activity);
    }

    @Override
    protected String getPathAndParams() {
        return "shop/add-delete-favorite?username="+ UserInfoManager.getInstance().getUser().getUsername()+
                "&type="+(isCollect.isCollection?3:1)+
                "&id="+commodityId;
    }

    @Override
    protected void handleResult(String result) {
        try{
            JSONObject jsonObject=new JSONObject(result);
            int code= jsonObject.getInt("code");
            if(code!=200) {
                return;
            }
            setHandleResultRunnable(new Runnable() {
                @Override
                public void run() {
                    isCollect.isCollection= !isCollect.isCollection;
                    collectButton.setText(isCollect.isCollection?"取消收藏":"收藏");
                    UserEntity user=UserInfoManager.getInstance().getUser();
                    user.setCollectionCount(user.getCollectionCount()+(isCollect.isCollection?1:-1));
                    UserInfoManager.getInstance().callRunner();
                    if (successRunnable!=null){
                        successRunnable.run();
                    }
                }
            });
        }catch (JSONException e){
            e.printStackTrace();
        }

    }
}
